package org.oslims.server.dao.hbm;

import java.util.List;

import org.hibernate.Query;
import org.oslims.domain.Request;
import org.oslims.server.dao.RequestDao;

public class HbmRequestDao extends HbmGenericDao<Request, Long> implements RequestDao {

	@Override
	public Request findLastRequest() {
		return (Request) this.getSession().createQuery("select r from Request as r where r.id = (select max(a.id) from Request a)").uniqueResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Request> findAllWithSamples() {
		Query q = this.getSession().createQuery("select distinct r from Request as r left join fetch r.samples order by r.code desc");

		return q.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Request> findAllWithSamples(int start, int length, String sortBy, Boolean desc) {
		String sortDirection = "asc";

		if (desc)
			sortDirection = "desc";

		Query q = this.getSession().createQuery("select distinct r from Request as r left join fetch r.samples order by r." + sortBy + " " + sortDirection);
		q.setFirstResult(start);
		q.setMaxResults(length);

		return q.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Request> findAllByState(String state) {
		Query q = this.getSession().createQuery("select distinct r from Request as r where r.state like :state order by r.code desc");
		q.setString("state", state);

		return q.list();
	}

}
